<script lang="ts" setup>
// ! 目前不支持doc、xls格式文件的预览
//引入VueOfficeDocx组件
import VueOfficeDocx from '@vue-office/docx';
import '@vue-office/docx/lib/index.css';

//引入VueOfficeExcel组件
import VueOfficeExcel from '@vue-office/excel';
import '@vue-office/excel/lib/index.css';

//引入VueOfficePdf组件
import VueOfficePdf from '@vue-office/pdf';

import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
const router = useRouter();
const fileText: any = undefined;
const data = reactive({
  loading: false,
  fileList: [],
  fileType: 'xlsx',
  docxSrc: '',
  excelSrc: '/template.xlsx',
  pdfSrc: '',

  codemirror: false,
  fileText,
  refreshCodemirrorKey: 0,
});
const customUpload = async (info: any) => {
  data.loading = true;
  console.log(info);
  let suffixName = info.file.name.split('.').pop();
  data.fileType = suffixName;
  data.codemirror = false;

  let fileReader = new FileReader();
  fileReader.readAsArrayBuffer(info.file);

  if (['docx', 'doc'].includes(suffixName)) {
    if (suffixName === 'doc') {
      message.info('请上传docx格式的文件');
      return;
    }
    fileReader.onload = () => {
      data.docxSrc = fileReader.result;
    };
  } else if (['xlsx', 'xls'].includes(suffixName)) {
    if (suffixName === 'xls') {
      message.info('请上传xlsx格式的文件');
      return;
    }
    fileReader.onload = () => {
      data.excelSrc = fileReader.result;
    };
  } else if (['pdf'].includes(suffixName)) {
    fileReader.onload = () => {
      data.pdfSrc = fileReader.result;
    };
  } else if (
    ['cpp', 'java', 'sql', 'py', 'vue', 'html', 'js', 'json', 'css', 'xml', 'rust', 'md'].includes(
      suffixName,
    )
  ) {
    // 文本，启用 Codemirror
    data.codemirror = true;

    data.fileText = await readFileAsync(info.file);
    data.refreshCodemirrorKey++;
  } else {
    // message.info('该格式暂不支持查看！');

    data.codemirror = true;
    data.fileText = await readFileAsync(info.file);
    data.refreshCodemirrorKey++;
  }
  data.loading = false;
};
const handleChange = async (e: any) => {
  let file = e.target.files[0];
  let suffixName = file.name.split('.').pop();
  data.fileType = suffixName;
  data.codemirror = false;

  let fileReader = new FileReader();
  fileReader.readAsArrayBuffer(file);

  if (['docx', 'doc'].includes(suffixName)) {
    if (suffixName === 'doc') {
      message.info('请上传docx格式的文件');
      return;
    }
    fileReader.onload = () => {
      data.docxSrc = fileReader.result;
    };
  } else if (['xlsx', 'xls'].includes(suffixName)) {
    if (suffixName === 'xls') {
      message.info('请上传xlsx格式的文件');
      return;
    }

    // 使用blob文件流
    let blob = new Blob([file], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    });
    data.excelSrc = URL.createObjectURL(blob);
    // 读取文件的ArrayBuffer
    // fileReader.onload = () => {
    //   data.excelSrc = fileReader.result;
    // };

    // data.excelSrc = URL.createObjectURL(file);
  } else if (['pdf'].includes(suffixName)) {
    fileReader.onload = () => {
      data.pdfSrc = fileReader.result;
    };
  } else if (
    ['txt', 'vue', 'json', 'java', 'sql', 'js', 'css', 'xml', 'html', 'yaml', 'md', 'py'].includes(
      suffixName,
    )
  ) {
    // 文本，启用 Codemirror
    data.codemirror = true;

    data.fileText = await readFileAsync(file);
    data.refreshCodemirrorKey++;
  } else {
    // message.info('该格式暂不支持查看！');

    data.codemirror = true;
    data.fileText = await readFileAsync(file);
    data.refreshCodemirrorKey++;
  }
};
const rendered = () => {
  console.log('渲染完成');
};
const errorHandler = () => {
  console.log('渲染失败');
};

// 读取文本文件内容
const readFileAsync = (file: Blob | File) => {
  return new Promise((resolve, reject) => {
    // 读取文件里面的内容返回
    var reader = new FileReader();
    // 以文本格式读取文件
    reader.readAsText(file, 'UTF-8');
    reader.onload = function (event) {
      resolve(event.target.result);
    };
    reader.onerror = function (event) {
      reject(event.target);
    };
  });
};

onMounted(() => {});
</script>
<template>
  <div class="content">
    <a-space class="mb-1 flex-wrap">
      <!-- accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" -->
      <a-upload
        v-model:file-list="data.fileList"
        :customRequest="customUpload"
        name="file"
        :multiple="false"
        :showUploadList="false"
      >
        <a-button :loading="data.loading" type="primary">选择文件</a-button>
      </a-upload>
      <input type="file" ref="fileButton" @change="handleChange" />
      <a-tag color="purple" v-if="data.fileType">.{{ data.fileType }} </a-tag>
      <a-button type="primary" danger @click="() => router.push('/index')">文件导出</a-button>
      <a-button type="primary" danger @click="() => router.push('/common')">lanuage theme</a-button>
      <!-- <a-button type="primary" danger @click="() => router.push('/sendEmail')"
        >nodemailer 发送邮箱</a-button
      > -->
    </a-space>
    <div class="mb-1 color-red-500">
      支持预览文件: pdf, xlsx, docx, cpp, java, sql, py, vue, html, js, json, css, xml, rust, md,
      txt, log, fa, fasta, tsv, csv 等各种文本文件
    </div>
    <!-- office -->
    <div v-if="!data.codemirror">
      <!-- docx -->
      <vue-office-docx
        v-if="data.fileType === 'docx'"
        :src="data.docxSrc"
        style="height: 80vh"
        @rendered="rendered"
        @error="errorHandler"
      />
      <!-- excel -->
      <vue-office-excel
        v-else-if="data.fileType === 'xlsx'"
        :src="data.excelSrc"
        style="height: 80vh"
        @rendered="rendered"
        @error="errorHandler"
      />
      <!-- pdf -->
      <vue-office-pdf
        v-else-if="data.fileType === 'pdf'"
        :src="data.pdfSrc"
        style="height: 100vh"
        @rendered="rendered"
        @error="errorHandler"
      />
    </div>
    <!-- 文本 -->
    <div v-else class="mt--6">
      <Codemirror :fileText="data.fileText" :fileType="data.fileType" />
      <!-- :key="data.refreshCodemirrorKey" -->
    </div>
  </div>
</template>

<style lang="less" scoped>
.content {
  width: 90vw;
  min-height: 90vh;
  margin: 3vh auto;
  padding: 20px;
  outline: 1px dashed #999;
}
</style>
